import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { removeUser, queryAccessToken, fakeAccountLogin, getCaptcha, postCaptcha } from '@/services/api';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    geetest: null,
  },

  effects: {
    * login({ payload }, { call, put }) {
      const { username, password, type } = payload

      const response = yield call(fakeAccountLogin, { username, password, });

      // 扩展
      response.type = type
      if (response.status) {
        response.currentAuthority = 'admin';
      } else {
        response.currentAuthority = 'guest';
      }
      /**
       * @Author   WangWei
       * @DateTime 2018-10-26
       * @param    {[type]}   response.status [根据前端需求转换个别参数]
       * @return   {[type]}                   [description]
       */
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

      // Login successfully
      if (response.status) {
        // 存储 token
        const { data } = response
        localStorage.setItem('token', data.token)
        localStorage.setItem(`token:timestamp`, Date.now())

        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let {
          redirect
        } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.startsWith('/#')) {
              redirect = redirect.substr(2);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
      }
    },

    /**
     *  获取滑块儿验证码
     */

    * getCaptcha({ payload }, { call, put }) {
      const geetest = yield call(getCaptcha, payload);
      // console.log(geetest, 'geetest123')
      // register geetest
      yield put({
        type: 'saveGeetest',
        payload: {
          geetest
        },
      });
    },

    * logout(_, { call, put }) {
      const response = yield call(removeUser);
      console.log(response, 123);
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
    },

    * tokenUpdate(_, { call, put }) {
      const response = yield call(queryAccessToken);
      console.log(response, 'tokenUpdate');
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        errcode: payload.errcode,
        status: payload.status,
        type: payload.type,
      };
    },
    saveGeetest(state, { payload }) {
      return {
        ...state,
        geetest: payload.geetest,
      };
    },
  },
};